package org.osito.jbehave.junit;

import static java.util.Arrays.asList;

import org.jbehave.core.ConfigurableEmbedder;
import org.jbehave.core.embedder.Embedder;
import org.jbehave.core.io.StoryPathResolver;
import org.jbehave.core.reporters.NullStoryReporter;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JUnitStoryRunner.class)
public class JUnitStory extends ConfigurableEmbedder {

	private JUnitFormat format;
	private boolean hiddenDryRun = false;

	public JUnitStory() {
	}

	public void setFormat(JUnitFormat format) {
		this.format = format;
	}

	public void setHiddenDryRun(boolean dryRun) {
		this.hiddenDryRun = dryRun;
	}

	@Test
	public void run() throws Throwable {
		Embedder embedder = configuredEmbedder();
		if (hiddenDryRun) {
			configureForHiddenDryRun(embedder);
		} else {
			configureForNormalRun(embedder);
		}
		StoryPathResolver pathResolver = embedder.configuration().storyPathResolver();
		String storyPath = pathResolver.resolve(this.getClass());
		embedder.runStoriesAsPaths(asList(storyPath));
	}

	private void configureForHiddenDryRun(Embedder embedder) {
		embedder.configuration() //
				.doDryRun(true) //
				.useDefaultStoryReporter(new NullStoryReporter()) //
				.useStoryReporterBuilder(null);

	}

	private void configureForNormalRun(Embedder embedder) {
		if (format != null) {
			format.setPendingStepStrategy(embedder.configuration().pendingStepStrategy());
			embedder.configuration().storyReporterBuilder().withFormats(format);
		}
	}

}
